<template>
  <div class="collage-order">
    <div class="box">
      <div class="times">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        class="demo-form-inline"
      >
        <el-form-item label="开始时间:" prop="start_time">
          <el-date-picker
            v-model="ruleForm.start_time"
            type="datetime"
            placeholder="选择开始时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="结束时间:" prop="end_time">
          <el-date-picker
            v-model="ruleForm.end_time"
            type="datetime"
            placeholder="选择结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
    </div>
    <div class="tablebox" ref="tablebox">
      <el-table :data="list" :height="oHeight" style="width: 100%">
      <el-table-column
        prop="flashsale_goodsname"
        label="商品选择"
        show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.flashsale_goodsname || row.pgoods_name }}
        </template>
      </el-table-column>
      <el-table-column width="80">
        <template slot-scope="scope">
          <el-button @click="selection(scope)">选取</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="pgoods_storage" label="库存"> </el-table-column>
      <el-table-column label="售价(元)">
        <template slot-scope="scope">{{
          scope.row.pgoods_points / 100
        }}</template>
      </el-table-column>
      <el-table-column label="抢购价(元)">
        <template slot-scope="scope">
          <el-input v-model="scope.row.flashsale_goodsprice" />
        </template>
      </el-table-column>
      <el-table-column label="售出" prop="sale_num"></el-table-column>
      <el-table-column label="排序">
        <template slot-scope="scope">
          <el-input v-model="scope.row.flashsale_goodssort" />
        </template>
      </el-table-column>
      <el-table-column>
        <template slot-scope="scope">
          <el-button type="danger" @click="deleteItem(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    </div>
    <div class="bombtn">
      <el-button type="primary" @click="addGoods">新增</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
    </div>
    <el-drawer
      title="商品选择"
      size="60%"
      :visible.sync="drawer"
      @close="closeDrawer"
    >
      <div class="commodity-search">
        <span>商品名称:</span>
        <el-input v-model="searchName"></el-input>
        <span>商品ID:</span>
        <el-input v-model="searchId"></el-input>
        <el-button type="primary" @click="searchGoods">搜索</el-button>
      </div>
      <div class="commodity-table">
        <el-table :data="searchList" border height="650" style="width: 100%">
          <el-table-column
            prop="pgoods_id"
            label="商品ID"
            align="center"
            width="120"
          >
          </el-table-column>
          <el-table-column prop="pgoods_name" label="商品名称" align="center">
            <template slot-scope="scope">
              <span class="name" @click="chooseGoods(scope.row)">{{
                scope.row.pgoods_name
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="pgoods_price"
            label="售价(元)"
            align="center"
            width="120"
          >
            <template slot-scope="scope">{{
              scope.row.pgoods_points / 100
            }}</template>
          </el-table-column>
        </el-table>
      </div>
      <div class="tips">点击商品即可选择商品</div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="searchTotal"
      >
      </el-pagination>
    </el-drawer>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        start_time: "",
        end_time: "",
      },
      rules: {
        start_time: [
          { required: true, message: "请选择开始时间", trigger: "blur" },
        ],
        end_time: [
          { required: true, message: "请选择结束时间", trigger: "blur" },
        ],
      },
      list: [],
      drawer: false,
      searchList: [],
      searchName: "",
      searchId: "",
      searchShow: 1,
      searchPage: 1,
      searchSize: 10,
      searchTotal: 0,
      currentPage: 1,
      index: null,
      oHeight:0
    };
  },
  created() {
    if (this.$route.params.row) {
      this.getInfo(this.$route.params.row.id);
    }
  },
  mounted(){
    let h = this.$refs.tablebox.offsetHeight
    this.$nextTick(()=>{
      this.oHeight = h
    })
  },
  methods: {
    getInfo(id) {
      this.$http
        .post(
          "/admin/pointprod/index.php?act=flashsale&op=flashsale_edit_info",
          { id }
        )
        .then((res) => {
          if (res.code == 1) {
            this.list = res.data.flashsale_goods || [];
            this.ruleForm.start_time =
              res.data.flashsale_start + " " + res.data.flashsale_starttime;
            this.ruleForm.end_time =
              res.data.flashsale_end + " " + res.data.flashsale_endtime;
          } else {
            this.$message.warning(res.msg);
          }
          this.id = id;
        });
    },
    addGoods() {
      this.drawer = true;
      this.index = null;
    },
    closeDrawer() {},
    searchGoods() {
      let data = {};
      if (this.searchId != "") {
        data.pgoods_id = this.searchId;
      }
      if (this.searchName != "") data.pgoods_name = this.searchName;
      data.pgoods_show = this.searchShow;
      data.page = this.searchPage;
      data.pageSize = this.searchSize;
      this.$http
        .get("/admin/pointprod/index.php?act=pointGoods&op=list", {
          params: data,
        })
        .then((res) => {
          if (res.code == 1) {
            this.searchList = res.data.list;
            this.searchTotal = res.data.totalCount;
          } else {
            this.$message.warning(res.msg);
          }
        });
    },
    chooseGoods(row) {
      // if (this.list == null) this.list = [];
      var repeat = this.list.filter((v) => v.pgoods_id == row.pgoods_id);
      if (repeat.length > 0) {
        this.$message.warning("不能重复选取同一商品!");
        return;
      }
      if(row.pgoods_spec == '1'){
        // this.$message.warning("暂不支持多规格商品!");
        // return;
        var goodsdata = this.$http
        .post("/admin/pointprod/index.php?act=pointGoods&op=getSkuGoods", {pgoods_id:row.pgoods_id})
        .then((res) => {
          if (res.code == 1) {
            if (this.index == null) {//空的时候直接push
              console.log(this.index);
              for(var item of res.data){
                this.list.push(item);
              }
            } else {//不是空的时候先删除在push
              let checklist = [];
              for(var data of this.list){
                if(data.pgoods_id == this.index.pgoods_id){
                  checklist.push(data)
                }
              }
              let newchecklist = new Set(checklist);
              let minus = this.list.filter(x => !newchecklist.has(x));//两个数组的差集
              console.log(minus);
              this.list = minus;
              for(var item of res.data){
                this.list.push(item);
              }
            } 
            this.index = null;
          } else {
            this.$message.warning(res.msg);
            this.index = null;
          }
        });        
      }else{
        if (this.index == null) {
          this.list.push(row);
        } else {
          let checklist = [];
          for(var data of this.list){
            if(data.pgoods_id == this.index.pgoods_id){
              checklist.push(data)
            }
          }
          if(checklist.length > 1){
            this.list.splice(this.list.indexOf(checklist[0]),checklist.length,row)
          }else{
            this.list[this.list.indexOf(this.index)] = row;
          }
        }
        this.index = null;     
      }
      console.log(this.list);
      this.drawer = false;
    },
    selection(scope) {
      this.drawer = true;
      this.index = scope.row;
    },
    deleteItem(scope) {
      this.$confirm("确定删除该项吗?", "提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          if (scope.row.id) {//编辑的时候
            let data = {
              id: scope.row.id,
            };
            this.$http
              .post(
                "/admin/pointprod/index.php?act=flashsale&op=flashsale_del_goods",
                data
              )
              .then((res) => {
                this.getInfo(this.id);
              });
          } else {//新增的时候
              let checklist = []
              for(var data of this.list){
                console.log(data.pgoods_id);
                console.log(scope.row.pgoods_id);
                if(data.pgoods_id == scope.row.pgoods_id){
                  //  this.list.splice(this.list.indexOf(data), 1);
                  checklist.push(data)
                }
              }
              // let newlist = new Set(this.list);
              let newchecklist = new Set(checklist);
              let minus = this.list.filter(x => !newchecklist.has(x));//两个数组的差集
              console.log(minus);
              this.list = minus;
              this.$message.success("删除成功!");            
            // this.list.splice(scope.$index, 1);
          }
        })
        .catch((_) => {});
    },
    submit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          if (this.list == null || this.list.length == 0) {
            this.$message.warning("请选取商品!");
            return;
          }
          var price = this.list.filter(
            (v) => !v.flashsale_goodsprice || v.flashsale_goodsprice <= 0
          ).length;
          if (price > 0) {
            this.$message.warning("请填写抢购价,且抢购价必须大于0!");
            return;
          }
          var s = this.ruleForm.start_time.substring(0, 10);
          var st = this.ruleForm.start_time.substring(
            this.ruleForm.start_time.length,
            11
          );
          var e = this.ruleForm.end_time.substring(0, 10);
          var et = this.ruleForm.end_time.substring(
            this.ruleForm.end_time.length,
            11
          );
          let arr = {
            id: this.id || "",
            flashsale_start: s || "",
            flashsale_end: e || "",
            flashsale_starttime: st || "",
            flashsale_endtime: et || "",
            goods: [],
          };
          this.list.map((v) => {
            let item = {
              goodsId: v.pgoods_id || "",
              goodsname: v.pgoods_name || "",
              goodsPrice: v.pgoods_points / 100  || "",
              flashsale_goodsprice: v.flashsale_goodsprice || "",
              sale_num: v.sale_num || '',
              flashsale_goodssort: v.flashsale_goodssort || "",
              goods_sku:v.sku?v.sku:v.goods_sku,
            };
            arr.goods.push(item);
          });
          this.$http
            .post(
              "/admin/pointprod/index.php?act=flashsale&op=flashsale_edit",
              arr
            )
            .then((res) => {
              if (res.code == 1) {
                this.$message.success(res.msg);
              } else {
                this.$message.warning(res.msg);
              }
            });
        } else {
          return false;
        }
      });
    },
    handleSizeChange(val) {
      this.searchSize = val
      this.searchGoods()
    },
    handleCurrentChange(val) {
      this.searchPage = val
      this.searchGoods()
    },
  },
};
</script>

<style lang="scss" scoped>
.collage-order {
  height: 94%;
  .box {
    height: 100%;
    display: flex;
    flex-direction: column;
    .tablebox {
      flex: 1;
    }
  }
}
.times {
  margin-top: 20px;
}
.el-form {
  display: flex;
  .el-form-item {
    display: flex;
  }
}
.el-date-editor {
  margin: 0 20px 0 0;
}
.bombtn {
  height: 40px;
  padding-top: 10px;
}
.el-drawer {
  .commodity-search {
    display: flex;
    align-items: center;
    padding: 20px;
    .el-input {
      width: 20%;
      margin: 0 15px;
    }
  }
  .commodity-table {
    padding: 10px 20px;
    .name {
      color: #409eff;
      cursor: pointer;
      border-bottom: 1px solid #409eff;
    }
  }
  .tips {
    width: 100%;
    text-align: center;
  }
  .el-pagination {
    display: flex;
    justify-content: flex-end;
    padding-right: 25px;
  }
  .name {
    color: #409eff;
    cursor: pointer;
    border-bottom: 1px solid #409eff;
  }
}
</style>
